#include "MCEIRService.h"
#include "DriverManager.h"
#include "Killer.h"
#include "RegKey.h"
#include "MceIrSession.h"

MCEIRService::MCEIRService( const char * arg )
{
	m_Name = "OpenMceIrService";

	if ( arg == NULL || arg[0] == 0 )
	{
		if ( !Execute() )
		{					
			PrintLastError("Execute failed");
		}		
		return;
	}

	char o;
	if ( ( arg[0] == '/' ) || ( arg[0] == '-' ) )
		o = arg[1];
	else
		o = ' ';

	
	switch (o)
	{
	case 'i':
		if ( ! Install() )
		{			
			PrintLastError("Install failed");
		}
		else
		{
			Print( (m_Name + " Installed").c_str() );
		}
		break;
	case 'u':
		if ( !Remove() )
		{			
			PrintLastError("Uninstall failed");
		}
		else
		{
			Print(m_Name + " Removed");
		}	
		break;
	case 's':
		if ( !Start() )
		{			
			PrintLastError("Start failed");
		}
		else
		{
			Print(m_Name + " Started");
		}
		break;

	case 'q':
		if ( !Stop() )
		{			
			PrintLastError("Stop failed");
		}
		else
		{
			Print(m_Name + " Stopped");
		}

		break;
	case 't':
		if ( ! ConsoleMode() )
		{
			PrintLastError("Test / ConsoleMode failed");
		}
		else
		{
			Print(m_Name + "Test / Console Mode Started");
		}
		break;
	
	default:
		Print("Unknown Commandline Options\r\n");
	case 'h':
		Print( "** OpenMceIrService **\r\n");
		Print( "/i\tInstall Service");
		Print( "/u\tUninstall Service");
		Print( "/s\tStart Service");
		Print( "/q\tStop Service");
		Print( "/t\tStart in test (console) mode");
		Print( "/?\tThis Help");		
	}
}

const char * MCEIRService::GetName ( )
{
	return m_Name.c_str();
}

TcpSessionPtr MCEIRService::sessionFactory ( boost::asio::io_service & s , DriverManager * driverManager)
{
	TcpSessionPtr tcpSession ( new MceIrSession( s, driverManager ) );
	return tcpSession;
}

void  MCEIRService::ServiceProc ()
{
	LogEvent(m_Name + " Starting");
	
	killer("ehtray.exe");

	DriverManager driverManager;
	
	
	TcpServer server(m_IOService, 12643, boost::bind(&MCEIRService::sessionFactory, this, _1, &driverManager ) );
	boost::asio::io_service::work work(m_IOService);
	m_IOService.run();

	LogEvent(m_Name + " Stopped");
}

void MCEIRService::Terminate()
{
	LogEvent(m_Name + "Shutting down...");
	TService::Terminate();
	m_IOService.stop();
}
